package com.hubu.blog.advice;

import com.hubu.blog.constant.ResponseCode;
import com.hubu.blog.entity.response.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 如果不设置basePackage,那么会把Knife4j的文档也拦截到导致报错
 */
@RestControllerAdvice(basePackages = "com.hubu.blog.controller")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除Knife4j/Swagger的Controller
        if (returnType.getDeclaringClass().getName().contains("springfox")
                || returnType.getDeclaringClass().getName().contains("knife4j")) {
            return false;
        }

        // 排除已经包装过的响应
        return !returnType.getParameterType().equals(Result.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 处理void返回类型
        if (body == null && returnType.getParameterType().equals(void.class)) {
            return Result.builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .message(ResponseCode.SUCCESS.getMessage())
                    .build();
        }

        // 已经包装过的直接返回
        if (body instanceof Result) {
            return body;
        }

        // 正常返回包装
        return Result.builder()
                .code(ResponseCode.SUCCESS.getCode())
                .message(ResponseCode.SUCCESS.getMessage())
                .data(body)
                .build();
    }
}